﻿/*
    This file is part of nDoctor Light

    NDoctor is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    NDoctor is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with NDoctor.  If not, see <http://www.gnu.org/licenses/>.
*/
namespace Probel.Ldoc.Dal.Incoherences
{
    using System.Linq;

    using NHibernate;
    using NHibernate.Linq;

    using Probel.Ldoc.Dal.Entities;
    using Probel.Ldoc.Dal.Helpers;
    using Probel.Ldoc.Dal.Properties;
    using Probel.Ldoc.Services.Dto;

    internal class ReputationSpellingRule : IRule
    {
        #region Methods

        /// <summary>
        /// Executes this rule and returns an
        /// <see cref="IncoherenceDto" /> if incoherence was found.
        /// Otherwise returns
        /// <c>Null</c>
        /// </summary>
        /// <param name="session">The session.</param>
        /// <returns>
        /// An incoherence or <c>Null</c> if nothing was found
        /// </returns>
        public IncoherenceDto Execute(ISession session)
        {
            var message = Messages.Rule_ReputationSpelling;
            var incoherences = (from item in session.Query<Reputation>().ToList()
                                group item by item.Name.RemoveDiacriticsLowerCase() into grp
                                where grp.ToList().Count() > 1
                                select new { Name = grp.Key }).Count();

            if (incoherences > 0)
            {
                return new IncoherenceDto()
                {
                    Message = string.Format(message, incoherences),
                    Level = Level.Error,
                    FixType = FixType.SpellingReputation,
                };
            }
            else { return null; }
        }

        #endregion Methods
    }
}